package com.cos.shop.dao.impl;

import com.cos.shop.dao.ProductDao;
import com.cos.shop.entity.Product;
import com.cos.shop.util.DBUtils;
import com.cos.shop.vo.CartVo;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author: COS
 * @time: 2023/5/11 10:31
 * @description:
 */
public class ProductDaoImpl implements ProductDao {
    private QueryRunner qr = new QueryRunner(DBUtils.getDataSource());


    @Override
    public Product getGoodsById(int id) throws SQLException {
        String sql = "select " +
                " `p_id` 'pid',p.`t_id` 'tid',`p_name` 'pname',`p_time` 'ptime'," +
                " `p_image` 'pimage',`p_price` 'pprice',`p_state` 'pstate'," +
                " `p_info` 'pinfo' , t_name 'tname'" +
                " from product p inner join type t" +
                " on p.t_id=t.t_id where p_id = ?";
        return qr.query(sql,new BeanHandler<>(Product.class),id);
    }

    @Override
    public List<Product> getProByPageWithTypeId(int typeId, int rowStart, int pageSize) throws SQLException {
        String sql = "select " +
                " `p_id` 'pid',`t_id` 'tid',`p_name` 'pname',`p_time` 'ptime'," +
                " `p_image` 'pimage',`p_price` 'pprice',`p_state` 'pstate',`p_info` 'pinfo' " +
                " from product where t_id = ? " +
                " limit ?,?";
        return qr.query(sql,new BeanListHandler<>(Product.class),
                typeId,rowStart,pageSize);
    }

    @Override
    public Long getProCount(int typeId) throws SQLException {
        return qr.query("select count(1) from product where t_id=?",
                new ScalarHandler<>(),typeId);
    }
}
